package ch3stacks;

import java.util.ArrayList;
import java.util.Stack;

class SetOfStacks {
	static final int MAX=2;
	ArrayList<Stack<Integer>> stacks = new ArrayList<>();
	
	public SetOfStacks() {
		stacks.add(new Stack<Integer>());
	}
	
	public int push(int n) {
		int last = stacks.size()-1;
		Stack<Integer> stack = stacks.get(last);
		if (stack.size() < MAX) {
			return stack.push(n);
		}
		else {
			Stack<Integer> newStack = new Stack<>();
			int push = newStack.push(n);
			if (push == n) {
				stacks.add(newStack);
			}
			return push;
		}
	}
	
	public int pop() {
		int last = stacks.size()-1;
		Stack<Integer> stack = stacks.get(last);
		Integer pop = stack.pop();
		if (stack.size() == 0) {
			stacks.remove(last);
		}
		return pop;
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (Stack<Integer> stack : stacks) {
			sb.append(stack.toString());
		}
		return sb.toString();
	}
}

public class Ex3 {

	public static void main(String ...strings) {
		int [] input = {1, 2, 3, 4, 5};
		SetOfStacks sos = new SetOfStacks();
		for (int n : input) {
			sos.push(n);
		}
		
		for (int i=0; i<input.length-3; i++) {
			System.out.println("pop="+sos.pop());
		}
		
		sos.push(11);
		sos.push(19);
		
		System.out.println(sos);
	}

}
